define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;

    require("jquery_ui")
    var config_panel = require("./config")
    var _tmp_list_item = require("./template/list-item.html");
    var _tmp_list_page = require("./template/list-page.html");
    var _tmp_tips_page = require("./template/tips_holder.html");
    var _tmp_bottomtips_page = require("./template/tips_bottom_holder.html");
    var _tmp_placeholder_page = require("./template/placeholder.html");
    var Design = function() {
        this.phone_container = $("#js_phone_container");
        this.config_container = $("#js_config_container");
        this.basemodule=$("#basemodule");
        this.activitymodule=$("#activitymodule");
        this.config_container_title = $("#js_config_container_title");
        this.config_load = $(".js_load");
        this.dropped = false;
        this.config = window.design_config;
        if(window.design_config.module){
            if(window.design_config.module.base){
                this.basemodule.html(template("js_module_temp",{list:window.design_config.module.base}));
            }
            if(window.design_config.module.activity){
                this.activitymodule.html(template("js_module_temp",{list:window.design_config.module.activity}));
            }
        }
        this.widget = $(".js_widget");
        this.action = this.actionHandler();
        this.init();
    }
    Design.prototype.init = function(el) {
        this.dragHandler();
        var _self = this;
        $(document).on("click", '.js_del_item', function(e) {
            e && e.stopPropagation();
            var $this=$(this);
            config.msg.msgbox.confirm(config.lang.confirmRemoveModule, function(result) {
                if (result) {
                    var $itme = $this.closest('.list-item');
                    $itme.fadeOut(function() {
                        $itme.remove();
                        _self.getListNumber();
                    });
                    var data = {
                        wid: $itme.attr("wid")
                    };
                    method.postd(_self.config.widget_del, function(d) {
                        if(!config.issucceed(d)){
                            config.msg.error(d.message || config.lang.removeError, d.url);
                        }else{
                            _self.config_container_title.html("");
                            var $formList= $("form[wid="+data.wid+"]",_self.config_container);
                            if(!$formList.is(":hidden")&&$formList.length){
                                $(".js_tips",_self.config_container).show(); 
                            }
                            $formList.remove();
                            config.msg.suc(d.message || config.lang.removeSuccess);
                        }
                    }, data)
                }
            });
           
        });
        $(document).on('click', '.list-item', function(e) {
            if(!$(this).hasClass("js_nosortable")){
                _self.showConfig($(this).attr("wid"));
                _self.config_container_title.html("（" + $(this).data("title") + "）");
                $("#js_phone_container .list-item").removeClass("active");
                $(this).addClass("active");
            }
            
        });
    };

    Design.prototype.actionHandler = function() {
        var _self = this;
        return {
            add_widget: function(el) {
                var data = {
                    name: el.data("name")
                }
                method.postd(_self.config.widget_add, function(d) {
                    if (config.issucceed(d)) {
                        _self.getWidgetHtml(el, d.wid, data.name,el.data("title"));
                        _self.config_container_title.html("（"+el.data("title")+"）");
                        $("#js_phone_container .list-item").removeClass("active");
                        $("#js_phone_container .list-item[wid="+d.wid+"]").addClass("active");
                         
                    } else {
                        config.msg.error(d.message || config.lang.widgetError, d.url)
                    }
                }, data)
            }
        }
    },
    Design.prototype.getWidgetHtml = function(el, wid, name,title) {
        var html = $(_tmp_list_item.format(this.config.widget_get.format(wid, name,""), wid,title));
        var _this=this;
        el.append(html.html());
        el.attr("wid", wid).removeData("name");
        this.showConfig(wid);
        setTimeout(function(){
            _this.updateWidget();
        },2000);

    },
    Design.prototype.showConfig = function(wid) {
        var _self = this;
        $(".js_tips").hide();
        wid && (function() {
            var formsConfig = $('.config_panel form');
            var formConfig = $('.config_panel form[wid="' + wid + '"]');
            _self.config_load.removeClass('hd');
            if (formConfig.length > 0) {
                formConfig.show();
                formConfig.siblings("form").hide();
                _self.config_load.addClass('hd');
            } else {
                var name=$(".list-item[wid="+wid+"]",$("#js_phone_container")).data("name");
                $.ajax(_self.config.config_get.format(wid,name), {
                    type: "get",
                    dataType: "html"
                }).done(function(result) {
                    var $result = $(result);
                    _self.config_container.append($result);
                    $result.length > 0 && require.async("dist/form/init", function(form) {
                        $("button[type='submit']", $result).removeAttr('disabled');
                        form.init($result);
                        config_panel.init($result);
                    });
                }).fail(function() {
                    config.msg.info(config.lang.templateConfigLoadError)
                }).always(function() {
                    _self.config_load.addClass('hd');
                })
                formsConfig.hide();
            }


        })()
    };
    Design.prototype.getPageHtml = function(d) {
        var _self = this,prev=0,next=0,flag=true;
        d && $.each(d, function(index, item) {
            var title=$("div[data-name="+item.name+"]").data("title");
            if(item.name=="toptipsholder"){
                _self.phone_container.append(_tmp_tips_page.format(_self.config.widget_get.format(item.id, item.name,item.type), item.id,title,item.name))
            }else if(item.name=="bottomtipsholder"){
                _self.phone_container.append(_tmp_bottomtips_page.format(_self.config.widget_get.format(item.id, item.name,item.type), item.id,title,item.name))
            }else if(item.name=="placeholder"){
                _self.phone_container.append(_tmp_placeholder_page.format(_self.config.widget_get.format(item.id, item.name,item.type), item.id,title,item.name))
            }else{
               _self.phone_container.append(_tmp_list_item.format(_self.config.widget_get.format(item.id, item.name,item.type), item.id,title,item.name)) 
            }
        });
        d && $.each(d, function(index, item) {
            prev++;
            if(item.name=="placeholder"){
                flag=false;
            }
            return flag;
        });
        _self.actionNumber(prev-1,d.length-prev);
    },
    Design.prototype.updateWidget = function() {
        var items = $(".list-item:not('.tips_holder')", this.phone_container);
        var data = $.map(items, function(item, index) {
            return $(item).attr("wid");
        });
        data && method.postd(window.design_config.widget_update, function() {
            //不处理成功 
        }, {
            data: window.JSON.stringify(data)
        })
    },
    Design.prototype.dragHandler = function() {
        var _self = this;
        this.widget.draggable({
            connectToSortable: _self.phone_container,
            revert: "invalid",
            helper: "clone",
            cursor: "move",
            scroll: false
        });
        this.phone_container.droppable({
            accept: ".widget",
            greedy: !0,
            drop: function(e, a) {
                _self.dropped = false;
                _self.dropOpt($(a.draggable))
            }
        }).sortable({
            revert: true,
            placeholder: "place_holder",
            axis: "y",
            opacity: 0.5,
            appendTo: _self.phone_container,
            connectWith: "#js_widget_list",
            cancel: ":input,button,.list-item-del,.js_nosortable",
            start: function() {
                _self.dropped = true;
            },
            stop: function() {
                _self.updateWidget();
                _self.getListNumber();
            }
        });
    };
    Design.prototype.dropOpt = function(e) {
        var name = e.data();
        e.removeAttr('class').addClass('list-item').empty()
        this.action.add_widget(e);
    };
    Design.prototype.getListNumber=function(){//处理上下占位提示
        var _this=this;
        setTimeout(function() {
            var $list=$('.list-item',_this.phone_container),
            prev=0,next=0,flag=true,len=$list.length;
            $list.each(function(){
                prev++;
                if($(this).hasClass("place-holder")){
                    flag=false;
                }
                return flag;
            });
            prev=prev-1;
            next=len-prev-1;
            _this.actionNumber(prev,next);
        },0);
    };
    Design.prototype.actionNumber=function(prev,next){
        var $pre=$('.list-item.top_tips_holder',this.phone_container),
            $next=$('.list-item.bottom_tips_holder',this.phone_container);
        if (prev > 1) {
            $pre.addClass('hide');
        } else {
            $pre.removeClass('hide');
        }
        if (next > 1) {
            $next.addClass('hide');
        } else {
            $next.removeClass('hide');
        }
    };
    window.design_config && (function() {
        var ds = new Design();
        if(window.design_config.isHolder){
            if(window.design_config.data==undefined){
                window.design_config.data=[{
                    "name": "toptipsholder",
                    "type": -1,
                    "id": -1
                },{
                    "name": "placeholder",
                    "type":-2,
                    "id": -2
                },{
                    "name": "bottomtipsholder",
                    "type": -3,
                    "id": -3
                }];
            }else{
                if (window.design_config.data.length) {
                    window.design_config.data.unshift({
                        "name": "toptipsholder",
                        "type": -1,
                        "id": -1
                    });
                    window.design_config.data.push({
                        "name": "bottomtipsholder",
                        "type": -3,
                        "id": -3
                    });
                }else{
                    window.design_config.data = [{
                        "name": "toptipsholder",
                        "type": -1,
                        "id": -1
                    }, {
                        "name": "placeholder",
                        "type": -2,
                        "id": -2
                    }, {
                        "name": "bottomtipsholder",
                        "type": -3,
                        "id": -3
                    }];
                }
            }
        }
        if (window.design_config.data) {
            ds.getPageHtml(window.design_config.data);
        };
        window.setWidget = function(widget) {
            var item = $('.list-item[wid="' + widget.wid + '"]');
            $("iframe,.list-item-body,.list-item-cover", item).height(widget.height);
        }
        window.updateWidget = function(wid) {
            var $iframe = $('.list-item[wid="' + wid + '"] iframe');
            $iframe.attr("src", $iframe.attr("src"))
        }

    })()
})
